package com.syh.niceweibo.common;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.Date;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.widget.Toast;

import com.syh.niceweibo.LoginActivity;
import com.syh.niceweibo.R;
import com.weibo.net.WeiboException;

public class Utils {
	private final static String TAG = "ImagesUtils";

	public static boolean download(String uri) throws Exception {

		if (uri == null || uri.length() == 0) {
			return false;
		}

		File file = Utils.get(uri);
		if (file == null) {
			return false;
		}

		if (file.exists()) {
			return true;
		}

		URL url = new URL(uri);
		URLConnection uCon = url.openConnection();
		uCon.setConnectTimeout(3000);
		uCon.setReadTimeout(3000);
		InputStream inputStream = uCon.getInputStream();
		// Log.d("DDD", "download size " + inputStream.available());
		OutputStream output = new FileOutputStream(file);
		byte[] buffer = new byte[1024];
		int length = 0;
		while ((length = inputStream.read(buffer)) != -1) {
			output.write(buffer, 0, length);
		}
		output.close();
		return true;
	}

	private static String getCacheDir() {
		return Environment.getExternalStorageDirectory().getAbsolutePath()
				+ File.separator + Constants.APP_DIR + File.separator
				+ Constants.CACHE_DIR;
	}

	private static File get(String url) {
		if (url == null) {
			return null;
		}

		String path = getCacheDir();
		File dir = new File(path);
		if (!dir.exists()) {
			dir.mkdirs();
		}
		return new File(path, URLEncoder.encode(url));
	}

	public static void deleteCache() {
		String path = getCacheDir();
		File dir = new File(path);
		deleteDir(dir);
	}

	private static void deleteDir(File dir) {
		if (dir.exists()) {
			if (dir.isDirectory()) {
				File[] fileList = dir.listFiles();
				if (fileList == null || fileList.length == 0) {
					dir.delete();
				} else {
					for (File f : fileList) {
						deleteDir(f);
					}
				}
			} else {
				dir.delete();
			}
		}
	}

	/**
	 * load bitmap from local memory
	 * 
	 * @param context
	 * @param url
	 * @return
	 */
	public static Bitmap getLocalImg(String url,final int outW) {
		if (url == null) {
			return null;
		}
		try {
			File file = get(url);
			if (file != null && file.exists() && file.isFile()) {
				String path=file.getAbsolutePath();
				if (LogUtils.DEBUG)
					LogUtils.d(TAG,
							"get local file path:" + path+ " url:" + url);
				
				//
				int sampleSize = 1;
                Options opts = new Options();
                if(outW>0){
                	// Compute the closest power-of-two scale factor
                    // and pass that to sBitmapOptionsCache.inSampleSize, which will
                    // result in faster decoding and better quality
                    opts.inJustDecodeBounds = true;
                    BitmapFactory.decodeFile(path, opts);
                    int outH=(int) ((outW*1.0*opts.outHeight)/(opts.outWidth*1.0));
//                    int scale = 1;  
                    int nextWidth = opts.outWidth ;
                    int nextHeight = opts.outHeight ;
                    if(url.equals("http://ww4.sinaimg.cn/large/75b508bfgw1dsioqjnhe7j.jpg")){
                    	if(LogUtils.DEBUG)LogUtils.d(TAG,"oom nextWidth:"+nextWidth+" nextHeight:"+nextHeight+" outH:"+outH+" outW:"+outW);
                    }
//                    while (true) {  
//                        if (nextWidth / 2 >= outW && nextHeight / 2 >= outH) {  
//                        	nextWidth /= 2;  
//                            nextHeight /= 2;  
//                            sampleSize*=2;
//                        } else {  
//                            break;  
//                        }  
//                    }  

                    
                    while (nextWidth>outW && nextHeight>outH) {
                        sampleSize <<= 1;
                        nextWidth >>= 1;
                        nextHeight >>= 1;
                    }
                    opts.inSampleSize = sampleSize;
                    opts.inJustDecodeBounds = false;
                }
                
                try {
					return BitmapFactory.decodeFile(path, opts);
				} catch (Exception e) {
					e.printStackTrace();
				} catch (OutOfMemoryError oom){
					oom.printStackTrace();
					if(LogUtils.DEBUG)LogUtils.e(TAG, "decodeFile oom:"+path+" url:"+url+" inSampleSize:"+opts.inSampleSize+" outW:"+outW+" opts.W:"+opts.outWidth+" opts.H:"+opts.outHeight);
				}
                return null;
				
			} else {
				if (LogUtils.DEBUG)
					LogUtils.e(TAG, "Failed to get image from local path:"
							+ url
							+ ",maybe the res havn't been downloaded before.");
				return null;
			}
		} catch (Exception e) {
			if (LogUtils.DEBUG)
				LogUtils.e(TAG, "Failed to get image from local path:" + url
						+ ",e:" + e.toString());
			e.printStackTrace();
			return null;
		}
	}

	public static void storeWeiboAccessInfo(Context context, String token,
			String expires_in, String uid) {
		if (LogUtils.DEBUG)
			LogUtils.d(TAG, "storeWeiboAccessInfo token:" + token
					+ "expires_in:" + expires_in + "uid:" + uid);
		PreferenceManager.getDefaultSharedPreferences(context).edit()
				.putString(Constants.WB_ACCESS_TOKEN, token)
				.putString(Constants.WB_EXPIRES_IN, expires_in)
				.putString(Constants.WB_UID, uid).commit();
	}

	public static String getAccessToken(Context context) {
		return PreferenceManager.getDefaultSharedPreferences(context)
				.getString(Constants.WB_ACCESS_TOKEN, null);
	}
	
	public static boolean needLogin(Context context){
		if(TextUtils.isEmpty(getAccessToken(context))){
			return true;
		}else{
			return false;
		}
	}

	public static String getUID(Context context) {
		return PreferenceManager.getDefaultSharedPreferences(context)
				.getString(Constants.WB_UID, null);
	}

	public static String getUserIcon(Context context) {
		return PreferenceManager.getDefaultSharedPreferences(context)
				.getString(Constants.WB_ICON, null);
	}

	public static String getUserName(Context context) {
		return PreferenceManager.getDefaultSharedPreferences(context)
				.getString(Constants.WB_NAME, null);
	}

	public static void saveUserInfo(Context context, String name, String icon) {
		PreferenceManager.getDefaultSharedPreferences(context).edit()
				.putString(Constants.WB_NAME, name)
				.putString(Constants.WB_ICON, icon).commit();
	}

	public static String getExpiresIn(Context context) {
		return PreferenceManager.getDefaultSharedPreferences(context)
				.getString(Constants.WB_EXPIRES_IN, null);
	}

	public static void clearWeiboInfo(Context context) {
		PreferenceManager.getDefaultSharedPreferences(context).edit()
				.remove(Constants.WB_ACCESS_TOKEN)
				.remove(Constants.WB_EXPIRES_IN).commit();
	}

	public static boolean isConnected(Context mContext) {
		ConnectivityManager cm = (ConnectivityManager) mContext
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
		if (activeNetwork == null) {
			return false;
		}
		return activeNetwork.isConnectedOrConnecting();
	}

	public static long formatTime(String dateTimeStr) {
		try {
			return new Date(dateTimeStr).getTime();
		} catch (Exception e) {
			e.printStackTrace();
			return 0;
		}
	}

	public static boolean getDisplayTypeIsList(Context context) {
		return PreferenceManager.getDefaultSharedPreferences(context)
				.getBoolean(Constants.PREF_DISPLAY_TYPE_IS_LIST, false);
	}

	public static void setDisplayType(Context context, boolean isTypeList) {
		PreferenceManager.getDefaultSharedPreferences(context).edit()
				.putBoolean(Constants.PREF_DISPLAY_TYPE_IS_LIST, isTypeList)
				.commit();
	}
	
	/**
     * invoked in UI-Thread
     * @param e
     * @param activity
     */
    public static void handleWeiboException(WeiboException e,Activity activity){
        if(LogUtils.DEBUG)LogUtils.e(TAG, "handleWeiboException: code:"+e.getStatusCode()+" msg:"+e.getMessage());
        switch(e.getStatusCode()){
            case 21327:{
                Intent intent=new Intent(activity,LoginActivity.class);
                activity.startActivity(intent);
                break;
            }
            case 20021:{
                Toast.makeText(activity, R.string.content_is_illegal, 1).show();
                break;
            }
            case 20019:{
                Toast.makeText(activity, R.string.content_is_repeat, 1).show();
                break;
            }
        }
    }
    
    public static int getColumnCount(Context context){
    	if(LogUtils.DEBUG)LogUtils.d(TAG, "widthPixels:"+context.getResources().getDisplayMetrics().widthPixels);
    	if(context.getResources().getDisplayMetrics().widthPixels<480){
    		return 2;
    	}else if(context.getResources().getDisplayMetrics().widthPixels>=960){
    		return 4;
    	}else{
    		return 3;
    	}
    }
}
